<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品类型" prop="goodsType">
        <el-cascader
          v-model="queryParams.goodsType"
          :options="cascaderOptions"
          :props="cascaderProps"
          placeholder="请选择商品类型（支持搜索）"
          clearable
          filterable
          :show-all-levels="true"
          @change="handleCascaderChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['shopping:goods:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['shopping:goods:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['shopping:goods:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['shopping:goods:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="goodsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="商品名称"
        align="center"
        prop="goodsName"
        v-if="columns[0].visible"
      />
      <el-table-column
        label="商品单价"
        align="center"
        prop="goodsPrice"
        v-if="columns[1].visible"
      />
      <el-table-column
        label="商品库存"
        align="center"
        prop="goodsNum"
        v-if="columns[2].visible"
      />
      <el-table-column
        label="商品类型"
        align="center"
        prop="typeName"
        v-if="columns[3].visible"
      />
      <el-table-column
        label="商品封面图"
        align="center"
        prop="goodsImg"
        v-if="columns[4].visible"
      >
        <template #default="scope">
          <el-image
            v-if="scope.row.goodsImg"
            :src="scope.row.goodsImg"
            style="width: 50px; height: 50px"
            :preview-src-list="[scope.row.goodsImg]"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="备注"
        align="center"
        prop="remark"
        v-if="columns[5].visible"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['shopping:goods:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['shopping:goods:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品详情对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      :width="dialogWidth"
      append-to-body
    >
      <el-form ref="goodsRef" :model="form" :rules="rules" :label-width="100">
        <el-row :gutter="20">
          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="商品单价" prop="goodsPrice">
              <el-input
                v-model="form.goodsPrice"
                placeholder="请输入商品单价"
              />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="商品库存" prop="goodsNum">
              <el-input v-model="form.goodsNum" placeholder="请输入商品库存" />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="商品类型" prop="goodsType">
              <el-cascader
                v-model="form.goodsType"
                :options="cascaderOptions"
                :props="cascaderProps"
                placeholder="请选择商品类型（支持搜索）"
                filterable
                :show-all-levels="true"
                @change="handleFormCascaderChange"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="商品封面图" prop="goodsImg">
              <el-upload
                ref="goodsImgUploadRef"
                :http-request="
                  (option) => customUploadRequest(option, 'goodsImg')
                "
                list-type="picture-card"
                :show-file-list="showGoodsImgFileList"
                :auto-upload="true"
                :limit="1"
                accept="image/*"
                :file-list="goodsImgFileList"
                @remove="(file) => handleRemove(file, 'goodsImg')"
                @preview="handlePictureCardPreview"
                @exceed="(files) => handleExceed(files, 'goodsImg')"
              >
                <el-icon><Plus /></el-icon>
                <template #tip>
                  <div class="el-upload__tip text-red">
                    建议尺寸800*600像素，且不超过2MB，只能选择1张图片
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="商品轮播图片" prop="bannerImg">
              <el-upload
                ref="bannerImgUploadRef"
                list-type="picture-card"
                :show-file-list="true"
                :auto-upload="false"
                :limit="3"
                accept="image/*"
                @change="
                  (uploadFile, uploadFiles) =>
                    handleFileChange(uploadFile, uploadFiles, 'bannerImg')
                "
                @exceed="(files) => handleExceed(files, 'bannerImg')"
                :before-upload="(file) => beforeUpload(file, 'bannerImg')"
                multiple
              >
                <el-icon><Plus /></el-icon>
                <template #tip>
                  <div class="el-upload__tip text-red">
                    最多3张，建议尺寸800*600像素，且不超过2MB，可连续选择最多3张图片
                  </div>
                </template>
              </el-upload>

              <!-- 显示已上传的文件 -->
              <div v-if="bannerImgFileList.length > 0" style="margin-top: 15px">
                <div style="margin-bottom: 10px; color: #666">
                  已上传 {{ bannerImgFileList.length }} 张图片：
                </div>
                <div style="display: flex; flex-wrap: wrap; gap: 10px">
                  <div
                    v-for="file in bannerImgFileList"
                    :key="file.uid"
                    style="position: relative"
                  >
                    <el-image
                      :src="file.url"
                      style="width: 80px; height: 80px; border-radius: 4px"
                      :preview-src-list="[file.url]"
                    />
                    <div style="position: absolute; top: -5px; right: -5px">
                      <el-button
                        type="danger"
                        size="small"
                        circle
                        @click="handleRemove(file, 'bannerImg')"
                      >
                        ×
                      </el-button>
                    </div>
                    <div
                      style="
                        font-size: 10px;
                        text-align: center;
                        margin-top: 5px;
                        color: #666;
                      "
                    >
                      {{ file.name }}
                    </div>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="商品详情图片" prop="detailsImg">
              <el-upload
                ref="detailsImgUploadRef"
                list-type="picture-card"
                :show-file-list="true"
                :auto-upload="false"
                :limit="10"
                accept="image/*"
                @change="
                  (uploadFile, uploadFiles) =>
                    handleFileChange(uploadFile, uploadFiles, 'detailsImg')
                "
                @exceed="(files) => handleExceed(files, 'detailsImg')"
                :before-upload="(file) => beforeUpload(file, 'detailsImg')"
                multiple
              >
                <el-icon><Plus /></el-icon>
                <template #tip>
                  <div class="el-upload__tip text-red">
                    最多10张，建议尺寸800*600像素，且不超过2MB，可连续选择最多10张图片
                  </div>
                </template>
              </el-upload>

              <!-- 显示已上传的文件 -->
              <div
                v-if="detailsImgFileList.length > 0"
                style="margin-top: 15px"
              >
                <div style="margin-bottom: 10px; color: #666">
                  已上传 {{ detailsImgFileList.length }} 张图片：
                </div>
                <div style="display: flex; flex-wrap: wrap; gap: 10px">
                  <div
                    v-for="file in detailsImgFileList"
                    :key="file.uid"
                    style="position: relative"
                  >
                    <el-image
                      :src="file.url"
                      style="width: 80px; height: 80px; border-radius: 4px"
                      :preview-src-list="[file.url]"
                    />
                    <div style="position: absolute; top: -5px; right: -5px">
                      <el-button
                        type="danger"
                        size="small"
                        circle
                        @click="handleRemove(file, 'detailsImg')"
                      >
                        ×
                      </el-button>
                    </div>
                    <div
                      style="
                        font-size: 10px;
                        text-align: center;
                        margin-top: 5px;
                        color: #666;
                      "
                    >
                      {{ file.name }}
                    </div>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="dialogVisible">
      <img
        w-full
        :src="dialogImageUrl"
        alt="Preview Image"
        style="width: 100%"
      />
    </el-dialog>
  </div>
</template>

<script setup name="Goods">
import { ElLoading } from "element-plus";
import {
  listGoods,
  getGoods,
  delGoods,
  addGoods,
  updateGoods,
} from "@/api/shopping/goods";
import { listGoodsType } from "@/api/shopping/goodsType";
import { upload, deleteImg } from "@/api/portal/banner";

const { proxy } = getCurrentInstance();

const goodsList = ref([]);
const goodsTypeOptions = ref([]);
const cascaderOptions = ref([]);
const cascaderProps = {
  value: "value", // 指定选项的值为选项对象的value属性
  label: "label", // 指定选项标签为选项对象的label属性
  children: "children", // 指定选项的子选项为选项对象的children属性
  expandTrigger: "click", // 次级菜单的展开方式
  checkStrictly: false, // 是否严格的遵守父子节点不互相关联
  emitPath: true, // 在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组
  multiple: false, // 是否多选
  hoverThreshold: 500, // hover 时展开菜单的灵敏度阈值
  showAllLevels: true, // 显示完整路径
};
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 图片上传相关
const showGoodsImgFileList = ref(false);
const showBannerImgFileList = ref(false);
const showDetailsImgFileList = ref(false);
const goodsImgFileList = ref([]);
const bannerImgFileList = ref([]);
const detailsImgFileList = ref([]);
const goodsImgUploadRef = ref(null);
const bannerImgUploadRef = ref(null);
const detailsImgUploadRef = ref(null);

// 批量上传相关
const isUploading = ref(false);
const uploadQueue = ref([]);

// 图片预览相关
const dialogVisible = ref(false);
const dialogImageUrl = ref("");

// 列显隐信息
const columns = ref([
  { key: 0, label: `商品名称`, visible: true },
  { key: 1, label: `商品单价`, visible: true },
  { key: 2, label: `商品库存`, visible: true },
  { key: 3, label: `商品类型`, visible: true },
  { key: 4, label: `商品封面图`, visible: true },
  { key: 5, label: `备注`, visible: true },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    goodsName: null,
    goodsPrice: null,
    goodsNum: null,
    goodsType: [], // 级联选择器使用数组
  },
  rules: {
    goodsName: [
      { required: true, message: "商品名称不能为空", trigger: "blur" },
    ],
    goodsPrice: [
      { required: true, message: "商品单价不能为空", trigger: "blur" },
    ],
    goodsNum: [
      { required: true, message: "商品库存不能为空", trigger: "blur" },
    ],
    goodsType: [
      {
        required: true,
        message: "商品类型不能为空",
        trigger: "change",
        validator: (rule, value, callback) => {
          if (!value || value.length === 0) {
            callback(new Error("商品类型不能为空"));
          } else {
            callback();
          }
        },
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 获取商品类型选项
function getGoodsTypeOptions() {
  console.log("开始获取商品类型选项...");
  listGoodsType({ hasPage: false })
    .then((response) => {
      console.log("API响应:", response);
      const allTypes = response.data || [];
      let arr = [];
      allTypes.forEach((item) => {
        if (!item.parentId) {
          arr.push({
            value: item.id,
            label: item.typeName,
            children: [],
          });
        }
      });
      console.log(allTypes);
      arr.forEach(item=>{
        allTypes.forEach(ktem=>{
          if(Number(item.value) ===Number(ktem.parentId)){
            item.children.push({
              value: ktem.id,
              label: ktem.typeName,
            });
          }
        })
      })
      goodsTypeOptions.value = arr;
      cascaderOptions.value =arr;
      console.log(cascaderOptions.value);
      
    })
    .catch((error) => {
      console.error("获取商品类型失败:", error);
      console.error("错误详情:", error.response || error.message);
      goodsTypeOptions.value = [];
      cascaderOptions.value = [];
    });
}

// 图片上传处理
const customUploadRequest = (option, type) => {
  const loadingInstance = ElLoading.service({
    text: "上传中...",
  });

  let formData = new FormData();
  formData.append("file", option.file);

  // 为上传请求添加防重复提交禁用标识
  upload(formData, { repeatSubmit: false })
    .then((response) => {
      // 生成唯一的UID，避免重复
      const uniqueUid = `${type}_${Date.now()}_${Math.random()
        .toString(36)
        .substr(2, 9)}`;
      const fileInfo = {
        url: response.fileUrl,
        uid: uniqueUid,
        name: option.file.name,
        status: "success",
      };

      // 根据类型参数处理不同的上传组件
      if (type === "goodsImg") {
        // 商品封面图只保留最新上传的一张
        goodsImgFileList.value = [fileInfo];
        showGoodsImgFileList.value = true;
      } else if (type === "bannerImg") {
        bannerImgFileList.value.push(fileInfo);
        showBannerImgFileList.value = true;
      } else if (type === "detailsImg") {
        detailsImgFileList.value.push(fileInfo);
        showDetailsImgFileList.value = true;
      }

      option.onSuccess(response, option.file);
      loadingInstance.close();
    })
    .catch((err) => {
      option.onError();
      loadingInstance.close();
    });
};

// 预览图片
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

// 级联选择器change事件处理
const handleCascaderChange = (value) => {
  console.log("查询表单级联选择器变化:", value);

  // 检查数据是否可用
  if (!checkCascaderData()) {
    proxy.$modal.msgWarning("商品类型数据未加载，请刷新页面重试");
    return;
  }

  // 保持数组格式，用于查询时传递完整的路径
  queryParams.value.goodsType = value || [];

  // 如果选择了值，显示提示信息
  if (value && value.length > 0) {
    const selectedPath = getCascaderPath(value);
    console.log("选择的商品类型路径:", selectedPath);
  }
};

// 表单级联选择器change事件处理
const handleFormCascaderChange = (value) => {
  console.log("表单级联选择器变化:", value);

  // 检查数据是否可用
  if (!checkCascaderData()) {
    proxy.$modal.msgWarning("商品类型数据未加载，请刷新页面重试");
    return;
  }

  // 保持数组格式，在提交时再处理
  form.value.goodsType = value || [];

  // 如果选择了值，显示提示信息
  if (value && value.length > 0) {
    const selectedPath = getCascaderPath(value);
    console.log("选择的商品类型路径:", selectedPath);
  }
};

// 获取级联选择器的显示路径
const getCascaderPath = (value) => {
  if (!value || value.length === 0) return "";

  const path = [];
  let currentOptions = cascaderOptions.value;

  for (let i = 0; i < value.length; i++) {
    const currentValue = value[i];
    const currentOption = currentOptions.find(
      (option) => option.value === currentValue
    );

    if (currentOption) {
      path.push(currentOption.label);
      currentOptions = currentOption.children || [];
    } else {
      break;
    }
  }

  return path.join(" > ");
};

// 检查级联选择器数据是否为空
const checkCascaderData = () => {
  if (!cascaderOptions.value || cascaderOptions.value.length === 0) {
    console.warn("级联选择器数据为空，请检查商品类型数据");
    return false;
  }
  return true;
};

// 上传前检查
const beforeUpload = (file, type) => {
  // 检查文件类型
  const isImage = file.type.startsWith("image/");
  if (!isImage) {
    proxy.$modal.msgError("只能上传图片文件");
    return false;
  }

  // 检查文件大小（2MB）
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    proxy.$modal.msgError("图片大小不能超过2MB");
    return false;
  }

  // 检查队列中的文件数量
  const currentQueueCount = uploadQueue.value.filter(
    (item) => item.type === type
  ).length;
  const currentFileListCount =
    type === "bannerImg"
      ? bannerImgFileList.value.length
      : detailsImgFileList.value.length;
  const maxLimit = type === "bannerImg" ? 3 : 10;

  if (currentQueueCount + currentFileListCount >= maxLimit) {
    const typeName = type === "bannerImg" ? "商品轮播图片" : "商品详情图片";
    proxy.$modal.msgError(`${typeName}最多只能上传${maxLimit}张图片`);
    return false;
  }

  // 阻止自动上传，但允许文件显示
  return false;
};

// 处理文件选择
const handleFileChange = (uploadFile, uploadFiles, type) => {
  // 检查是否是新增的文件（有raw属性且状态为ready的文件）
  if (uploadFile && uploadFile.raw && uploadFile.status === "ready") {
    uploadQueue.value.push({ file: uploadFile, type });

    // 自动开始上传
    setTimeout(() => {
      batchUploadImages(type);
    }, 100);
  }
};

// 批量上传图片
const batchUploadImages = async (targetType) => {
  if (isUploading.value) {
    return;
  }

  // 过滤出指定类型的文件
  const targetFiles = uploadQueue.value.filter(
    (item) => item.type === targetType
  );

  if (targetFiles.length === 0) {
    proxy.$modal.msgError("没有文件需要上传");
    return;
  }

  isUploading.value = true;
  const loadingInstance = ElLoading.service({
    text: "正在上传图片...",
  });

  try {
    // 串行上传，避免触发防重复提交机制
    const results = [];

    for (let i = 0; i < targetFiles.length; i++) {
      const { file, type } = targetFiles[i];
      let retryCount = 0;
      const maxRetries = 3;

      while (retryCount < maxRetries) {
        try {
          // 添加延迟避免重复提交
          if (i > 0) {
            await new Promise((resolve) => setTimeout(resolve, 1000));
          }

          const formData = new FormData();
          const fileToUpload = file.raw || file;
          formData.append("file", fileToUpload);

          // 为上传请求添加防重复提交禁用标识
          const response = await upload(formData, { repeatSubmit: false });

          // 生成唯一的UID
          const uniqueUid = `${type}_${Date.now()}_${Math.random()
            .toString(36)
            .substr(2, 9)}`;
          const fileInfo = {
            url: response.fileUrl,
            uid: uniqueUid,
            name: file.name,
            status: "success",
          };

          results.push({ status: "fulfilled", value: fileInfo });
          break;
        } catch (error) {
          retryCount++;

          if (retryCount < maxRetries) {
            await new Promise((resolve) => setTimeout(resolve, 2000));
          } else {
            proxy.$modal.msgError(`文件 ${file.name} 上传失败，已跳过`);
            results.push({ status: "rejected", reason: error });
          }
        }
      }
    }

    // 统计成功和失败的数量
    const successful = results.filter(
      (result) => result.status === "fulfilled"
    ).length;
    const failed = results.filter(
      (result) => result.status === "rejected"
    ).length;

    // 将成功上传的文件添加到对应的文件列表
    results.forEach((result, index) => {
      if (result.status === "fulfilled") {
        const fileInfo = result.value;
        const { type } = targetFiles[index];

        if (type === "bannerImg") {
          bannerImgFileList.value.push(fileInfo);
          showBannerImgFileList.value = true;
        } else if (type === "detailsImg") {
          detailsImgFileList.value.push(fileInfo);
          showDetailsImgFileList.value = true;
        }
      }
    });

    if (failed > 0) {
      proxy.$modal.msgWarning(
        `上传完成: 成功 ${successful} 个，失败 ${failed} 个`
      );
    }

    // 从队列中移除已上传的文件
    uploadQueue.value = uploadQueue.value.filter(
      (item) => item.type !== targetType
    );

    // 清除上传组件的文件列表
    if (targetType === "bannerImg") {
      bannerImgUploadRef.value?.clearFiles();
    } else if (targetType === "detailsImg") {
      detailsImgUploadRef.value?.clearFiles();
    }

    proxy.$modal.msgSuccess("图片上传完成");
  } catch (error) {
    proxy.$modal.msgError("图片上传失败，请重试");
  } finally {
    isUploading.value = false;
    loadingInstance.close();
  }
};

// 处理超出限制
const handleExceed = (files, type) => {
  const typeName = type === "bannerImg" ? "商品轮播图片" : "商品详情图片";
  const maxLimit = type === "bannerImg" ? 3 : 10;
  proxy.$modal.msgError(`${typeName}最多只能上传${maxLimit}张图片`);
};

// 删除图片
const handleRemove = (file, type) => {
  const currentUrl = file.url;
  deleteImg({ url: currentUrl }).then((response) => {
    if (type === "goodsImg") {
      goodsImgFileList.value = goodsImgFileList.value.filter(
        (item) => item.uid !== file.uid
      );
    } else if (type === "bannerImg") {
      bannerImgFileList.value = bannerImgFileList.value.filter(
        (item) => item.uid !== file.uid
      );
    } else if (type === "detailsImg") {
      detailsImgFileList.value = detailsImgFileList.value.filter(
        (item) => item.uid !== file.uid
      );
    }
    proxy.$modal.msgSuccess("删除成功");
  });
};

/** 查询商品详情列表 */
function getList() {
  loading.value = true;

  // 处理查询参数中的商品类型
  const queryData = { ...queryParams.value };
  if (Array.isArray(queryData.goodsType) && queryData.goodsType.length > 0) {
    // 如果选择了级联选择器的值，取最后一个作为商品类型ID
    queryData.goodsType = queryData.goodsType[queryData.goodsType.length - 1];
  }

  listGoods(queryData).then((response) => {
    goodsList.value = response.rows.map((item) => {
      // 处理商品类型名称
      const goodsType = goodsTypeOptions.value.find(
        (type) => type.id === item.goodsType
      );
      if (goodsType) {
        if (goodsType.level === 1) {
          item.goodsTypeName = goodsType.typeName;
        } else if (goodsType.level === 2) {
          // 查找父级分类
          const parentType = goodsTypeOptions.value.find(
            (type) => type.id === goodsType.parentId
          );
          if (parentType) {
            item.goodsTypeName = `${parentType.typeName} > ${goodsType.typeName}`;
          } else {
            item.goodsTypeName = goodsType.typeName;
          }
        }
      } else {
        item.goodsTypeName = "";
      }
      return item;
    });
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
  clearUploadFiles();
}

// 清除上传文件
function clearUploadFiles() {
  goodsImgUploadRef.value?.clearFiles();
  bannerImgUploadRef.value?.clearFiles();
  detailsImgUploadRef.value?.clearFiles();
  goodsImgFileList.value = [];
  bannerImgFileList.value = [];
  detailsImgFileList.value = [];
  uploadQueue.value = [];
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    goodsName: null,
    goodsPrice: null,
    goodsNum: null,
    goodsType: [], // 级联选择器使用数组
    goodsImg: null,
    bannerImg: null,
    detailsImg: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
  };
  proxy.resetForm("goodsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.goodsType = []; // 重置级联选择器为空数组
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加商品详情";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getGoods(_id).then((response) => {
    form.value = response.data;

    // 处理商品类型级联选择器的值
    if (form.value.goodsType) {
      const goodsType = goodsTypeOptions.value.find(
        (type) => type.id === form.value.goodsType
      );
      if (goodsType && goodsType.level === 2) {
        // 如果是二级分类，需要构建完整的路径
        const parentType = goodsTypeOptions.value.find(
          (type) => type.id === goodsType.parentId
        );
        if (parentType) {
          form.value.goodsType = [parentType.id, goodsType.id];
        }
      } else if (goodsType && goodsType.level === 1) {
        // 如果是一级分类，直接使用ID
        form.value.goodsType = [goodsType.id];
      }
    }

    // 处理图片数据
    if (form.value.goodsImg) {
      goodsImgFileList.value = [
        {
          url: form.value.goodsImg,
          uid: `goodsImg_${Date.now()}`,
          name: "商品封面图",
          status: "success",
        },
      ];
      showGoodsImgFileList.value = true;
    }

    if (form.value.bannerImg) {
      const bannerImgs = form.value.bannerImg.split(",").filter((img) => img);
      bannerImgFileList.value = bannerImgs.map((img, index) => ({
        url: img,
        uid: `bannerImg_${Date.now()}_${index}`,
        name: `轮播图${index + 1}`,
        status: "success",
      }));
      showBannerImgFileList.value = true;
    }

    if (form.value.detailsImg) {
      const detailsImgs = form.value.detailsImg.split(",").filter((img) => img);
      detailsImgFileList.value = detailsImgs.map((img, index) => ({
        url: img,
        uid: `detailsImg_${Date.now()}_${index}`,
        name: `详情图${index + 1}`,
        status: "success",
      }));
      showDetailsImgFileList.value = true;
    }

    open.value = true;
    title.value = "修改商品详情";
  });
}

/** 提交按钮 */
function submitForm() {
  // 处理商品类型值
  if (Array.isArray(form.value.goodsType)) {
    // 如果是数组（级联选择器的值），取最后一个值作为商品类型ID
    form.value.goodsType =
      form.value.goodsType[form.value.goodsType.length - 1];
  }

  // 处理图片数据
  if (goodsImgFileList.value.length > 0) {
    form.value.goodsImg = goodsImgFileList.value[0].url;
  }

  if (bannerImgFileList.value.length > 0) {
    form.value.bannerImg = bannerImgFileList.value
      .map((item) => item.url)
      .join(",");
  }

  if (detailsImgFileList.value.length > 0) {
    form.value.detailsImg = detailsImgFileList.value
      .map((item) => item.url)
      .join(",");
  }

  proxy.$refs["goodsRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateGoods(form.value).then((response) => {
          clearUploadFiles();
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addGoods(form.value).then((response) => {
          clearUploadFiles();
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除商品详情编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delGoods(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "shopping/goods/export",
    {
      ...queryParams.value,
    },
    `goods_${new Date().getTime()}.xlsx`
  );
}

getList();
getGoodsTypeOptions();

/** 动态计算字段数 **/
const fieldCount = ref(0);

onMounted(() => {
  // 统计表单字段数量
  fieldCount.value = [
    "goodsName",
    "goodsPrice",
    "goodsNum",
    "goodsType",
    "goodsImg",
    "bannerImg",
    "detailsImg",
    "remark",
  ].length;
});

const isTwoColumnForm = computed(() => fieldCount.value > 8);
const dialogWidth = computed(() => (isTwoColumnForm.value ? "80vw" : "600px"));
</script>
